package net.xmmpp.uc.im.bootstrap.web.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;

import static com.fasterxml.jackson.core.JsonToken.VALUE_STRING;

public class JsonToCodeConverter {
    public static void main(String[] args) throws Exception {
        String jsonStr = "{\"name\":\"John\", \"age\":30}"; // JSON字符串

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonStr);

        StringBuilder sb = new StringBuilder();
        sb.append("// Generated Java Code\n");
        sb.append("\n");
        sb.append("@Data\n");
        sb.append("public class MyPojo {\n");

        for (Iterator<String> fieldNames = rootNode.fieldNames(); fieldNames.hasNext(); ) {
            String fieldName = fieldNames.next();

            if (!rootNode.get(fieldName).isNull()) {
                sb.append("\tprivate ");

                switch (rootNode.get(fieldName).asToken()) {
                    case VALUE_STRING:
                        sb.append("String ");
                        break;

                    case VALUE_NUMBER_INT:
                        sb.append("int ");
                        break;

                    default:
                        throw new IllegalArgumentException("Unsupported data type in JSON.");
                }

                sb.append(fieldName + "; \n");
            }
        }

        sb.append("}\n");

        System.out.println(sb.toString());

        File file = new File("MyPojo.java");
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.write(sb.toString());
        writer.close();
    }
}